package com.meicet.adapter.utils

import androidx.lifecycle.LifecycleCoroutineScope
import kotlinx.coroutines.*

@OptIn(DelicateCoroutinesApi::class)
@Deprecated("不要用全局环境生成")
fun launchUI(block: suspend CoroutineScope.() -> Unit): Job {
    val blockWrapper: suspend CoroutineScope.() -> Unit = {
        block.invoke(this)
    }

    return GlobalScope.launch(context = Dispatchers.Main, block = blockWrapper)
}
@OptIn(DelicateCoroutinesApi::class)
@Deprecated("不要用全局环境生成")
fun <T> asyncIO(block: suspend CoroutineScope.() -> T): Deferred<T> {
    val blockWrapper: suspend CoroutineScope.() -> T = {
        block.invoke(this)
    }

    return GlobalScope.async(context = Dispatchers.IO, block = blockWrapper)
}
@OptIn(DelicateCoroutinesApi::class)
@Deprecated("不要用全局环境生成")
fun launchIO(block: suspend CoroutineScope.() -> Unit): Job {
    val blockWrapper: suspend CoroutineScope.() -> Unit = {
        block.invoke(this)
    }

    return GlobalScope.launch(context = Dispatchers.IO, block = blockWrapper)
}
@OptIn(DelicateCoroutinesApi::class)
fun LifecycleCoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit) {
    launch {
        withContext(Dispatchers.IO) {
            block.invoke(this)
        }
    }
}

@OptIn(DelicateCoroutinesApi::class)
fun LifecycleCoroutineScope.launchUI(block: suspend CoroutineScope.() -> Unit) {
    launch {
        withContext(Dispatchers.Main) {
            block.invoke(this)
        }
    }
}

fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit) {
    launch {
        withContext(Dispatchers.IO) {
            block.invoke(this)
        }
    }
}
// fun <T> async(block: suspend CoroutineScope.() -> T): Deferred<T> {
//    val blockWrapper: suspend CoroutineScope.() -> T = {
//        try {
//            block.invoke(this)
//        } catch (e: Exception) {
//            _e(e)
//            throw e
//        }
//    }
//
//    return GlobalScope.async(context = Dispatchers.Default, block = blockWrapper)
// }

// fun launch(block: suspend CoroutineScope.() -> Unit): Job {
//    val blockWrapper: suspend CoroutineScope.() -> Unit = {
//        try {
//            block.invoke(this)
//        } catch (e: Exception) {
//            _e(e)
//            throw e
//        }
//    }
//
//    return GlobalScope.launch(context = Dispatchers.Default, block = blockWrapper)
// }
